package com.gitee.huxing.course.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.gitee.huxing.course.config.exception.ServiceException;
import com.gitee.huxing.course.service.PlatFormOrderService;
import com.gitee.huxing.framework.redis.RedisWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description:
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.controller
 * @ClassName: TestController
 * @Author: huxing
 * @DateTime: 2021-09-17 下午4:32
 */
@Slf4j
@RestController
public class TestController {

    @Autowired
    PlatFormOrderService service;

    @Autowired
    RedisWrapper redisWrapper;

    @RequestMapping("/api/v1/apply")
    public String generalOrder(){
        return "下单成功, 您的购买订单号为: " +  this.service.purchase();
    }

    @RequestMapping("/api/v1/getOrder/{orderId}")
    public String queryOrder(@PathVariable("orderId") String orderId){
        // TODO: 尝试获取当前的锁, 超时设置3000L
        if (!redisWrapper.getLock(orderId, 30000L)){
            log.info("订单编号被锁定了: {}", DateUtil.now());
            return "您好，订单记录被锁定了" + DateUtil.now();
        }
        try {
            return "您好，您的订单记录为: " + JSONObject.toJSONString(this.service.
                    queryOrder(orderId));
        } finally {
            // TODO: 处理结束以后释放锁
            redisWrapper.releaseLock(orderId);
        }
    }
}
